/* sel.c */

#include <conio.h>
#include <code.h>

/* This program illustrates of CODE.H definitons to make C code /*
/* more readable. */

void trim(char *s)
/* Trim white space from both ends of string s */
BEGIN
    char    *pc, *pce;

    for (pc = s; *pc AND (*pc == ' ' OR *pc == '\t'); pc++);
    for (pce = pc; *pce > ' '; pce++);
    *pce = 0;
    strcpy(s, pc);
END

cdecl main(int argc, char *argv[])
BEGIN
    char    s[80], *clrstr, *pc;
    int     i, n;

    IF (argc < 2)
        cputs("Usage:   sel \"Prompt\" [max_no]\r\n");
        cputs("   Intended for use it batch files with ERRORLEVEL testing.\r\n");
        cputs("   Will output the prompt and wait for the user to input\r\n");
        cputs("   Y or N if max_no parameter is not present, or otherwise\r\n");
        cputs("   expects the input of number from 1 to max_no. Exits with\r\n");
        cputs("   errorlevel according to user input. Examples:\r\n");
        cputs("         sel \"Enter your selection form 1 to 5 \" 5\r\n");
        cputs("         sel \"Are you sure? (Y/N) \"\r\n");
        cputs("   The last line returns errorlevel 0 for N and 1 for Y\r\n");
        exit(255);
    ENDIF
    cputs(argv[1]);
    clrstr = "\r                                                                              \r";
    IF (argc > 2)               /* This is selection, get number 1..n */
        n = atoi(argv[2]);
        IF (n < 1 OR n > 25)
            cputs("Error in select.");
            exit(255);
        ENDIF
        REPEAT
            s[0] = 78;
            pc = cgets(s);
            trim(pc);
            i = atoi(pc);
            IF (i<1 OR i>n)
                cputs(clrstr);
                cputs(argv[1]);
            ENDIF
        UNTIL (i > 0 AND i <= n);
        exit(i);
    ELSE                        /* This is Y/N prompt, get Y or N */
        REPEAT
            s[0] = 78;
            pc = cgets(s);
            trim(pc);
            i = toupper(*pc);
            IF (i!='N' AND i!='Y')
                cputs(clrstr);
                cputs(argv[1]);
            ENDIF
        UNTIL (i == 'N' OR i == 'Y');
        exit (i=='Y');
    ENDIF
END
